package com.tbit.uqbike.client.service.impl;

import com.tbit.common.config.OssDefaultConfig;
import com.tbit.uqbike.client.constant.ReturnBikeMsgLogConstant;
import com.tbit.uqbike.client.constant.RideLogDetailConstant;
import com.tbit.uqbike.client.dao.core.FeeAppealDao;
import com.tbit.uqbike.client.dao.core.OssConfigDao;
import com.tbit.uqbike.client.dao.log.ReturnBikeMsgLogDao;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.FeeAppeal;
import com.tbit.uqbike.client.pojo.OssConfig;
import com.tbit.uqbike.client.pojo.ReturnBikeMsgLog;
import com.tbit.uqbike.client.pojo.RideLog;
import com.tbit.uqbike.client.service.AccountService;
import com.tbit.uqbike.client.service.FeeAppealService;
import com.tbit.uqbike.client.service.RideLogService;
import com.tbit.uqbike.client.util.DateTimeUtil;
import com.tbit.uqbike.client.util.aliyun.FileLoadUtils;
import com.tbit.uqbike.client.util.aliyun.OssFileUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author: ShiGuang
 * @create: 2021-12-13 13:34
 * @description: 费用申诉实现类
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class FeeAppealServiceImpl implements FeeAppealService {


    @Autowired
    private FeeAppealDao feeAppealDao;
    @Autowired
    private AccountService accountService;
    @Autowired
    private OssConfigDao ossConfigDao;
    @Autowired
    private RideLogService rideLogService;
    @Autowired
    private ReturnBikeMsgLogDao returnBikeMsgLogDao;
    @Autowired
    private OssDefaultConfig ossDefaultConfig;


    /**
     * 新增
     *
     * @param feeAppeal
     * @param list
     */
    @Override
    public void insert(FeeAppeal feeAppeal, List<MultipartFile> list) {

        // 重复操作判断
        String orderNO = feeAppealDao.getOrderNO(feeAppeal.getOrderNO());
        if (orderNO != null) {
            throw new BaseException("-102", "请勿重复操作");
        }

        // 图片保存到阿里云，并设置url地址
        if (list.size() > 0) {
            StringBuffer name = new StringBuffer();
            try {
                for (MultipartFile multipartFile : list) {
                    if (!FileLoadUtils.checkFileSize(multipartFile, 2, "M")) {
                        throw new BaseException("-4003", "图片过大");
                    }
                    String fileName = ossFileUpload(multipartFile, feeAppeal.getAccountId());
                    name.append(fileName).append(";");
                }
            } catch (Exception e) {
                log.error("图片上传失败,失败原因{}", e);
            }
            if (name.length() > 1) {
                name.delete(name.length() - 1, name.length());
            }
            if (!name.toString().equalsIgnoreCase("null")) {
                feeAppeal.setUrl(name.toString());
            }
        }

        //根据订单编号获取车辆
        RideLog rideLog = rideLogService.getByOrderNO(feeAppeal.getOrderNO());
        if (rideLog == null) {
            log.warn("骑行订单不存在");
        } else {
            String payTime = rideLog.getPayTime();
            if (payTime == null) {
                throw new BaseException("-3066", "订单未支付");
            }
            feeAppeal.setAccountId(rideLog.getAccountId());
            feeAppeal.setMachineNO(rideLog.getMachineNO());
            feeAppeal.setAddTime(DateTimeUtil.getNowTime());
            feeAppeal.setState(0);
            feeAppeal.setMoney(rideLog.getMoney().intValue());
            // 判断费用申诉期限,7天内
            if (DateTimeUtil.getHour(rideLog.getEndTime()) > 7 * 24) {
                throw new BaseException("-3065", "已经超过费用申诉期限");
            }
            feeAppealDao.insert(feeAppeal);
            ReturnBikeMsgLog log = returnBikeMsgLogDao.selectActualLog(feeAppeal.getOrderNO());
            if (log != null) {
                log.setReturnType(ReturnBikeMsgLogConstant.TYPE_COMPLAINT);
                returnBikeMsgLogDao.insert(log);
            }
        }
    }

    /**
     * 根据userId获取
     *
     * @param userId
     * @return
     */
    @Override
    public List<FeeAppeal> getByUserId(Integer userId) {
        return feeAppealDao.getByUserId(userId);
    }

    /**
     * 根据userId分页查询
     *
     * @param userId
     * @param rowCount
     * @param pageNO
     * @return
     */
    @Override
    public List<FeeAppeal> queryPage(Integer userId, Integer rowCount, Integer pageNO) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("start", (pageNO - 1) * rowCount);
        params.put("rowCount", rowCount);
        return feeAppealDao.queryPage(params);
    }

    /**
     * 获取总记录数
     *
     * @param userId
     * @return
     */
    @Override
    public Integer queryCount(Integer userId) {
        return feeAppealDao.queryCount(userId);
    }

    /**
     * 根据订单编号和用户id查询费用申诉信息
     *
     * @param orderNO
     * @param userId
     * @return
     */
    @Override
    public FeeAppeal getByOrderNo(String orderNO, Integer userId) {
        HashMap<String, Object> params = new HashMap<>();
        params.put("orderNO", orderNO);
        params.put("userId", userId);

        return feeAppealDao.getByOrderNOAndUserId(params);
    }

    @Override
    public Integer getNotRead(Integer userId) {

        return feeAppealDao.getNotRead(userId);
    }

    @Override
    public void edit(String orderNO, Integer userId) {
        FeeAppeal feeAppeal = getByOrderNo(orderNO, userId);
        if (feeAppeal == null) {
            throw new BaseException("-3067", "不存在此订单");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("orderNO", orderNO);
        if (feeAppeal.getState().equals(RideLogDetailConstant.FEE_APPEAL_SUCCESS)) {
            map.put("state", RideLogDetailConstant.FEE_APPEAL_SUCCESS_READ);
        } else if (feeAppeal.getState().equals(RideLogDetailConstant.FEE_APPEAL_FAIL)) {
            map.put("state", RideLogDetailConstant.FEE_APPEAL_FAIL_READ);
        } else {
            return;
        }
        feeAppealDao.edit(map);
    }

    @Override
    public String ossFileUpload(MultipartFile multipartFile, Integer accountId) {
        try {
            InputStream inputStream = multipartFile.getInputStream();
            // 阿里云配置
            OssConfig ossConfig = new OssConfig(ossDefaultConfig.getEndpoint(),
                    ossDefaultConfig.getAccessKeyId(),
                    ossDefaultConfig.getAccessKeySecret(),
                    "gx-feeappeal");

            //Account account = accountService.getByAdAccountId(feeAppeal.getAccountId());
            // 查询是否存在配置信息
            OssConfig ossConfigDB = ossConfigDao.getByAccountId(accountId);
            if (ossConfigDB != null) {
                ossConfig = ossConfigDB;
            }
            // 添加图片
            String imageId = UUID.randomUUID().toString();
            // 上传阿里云
            String fileName = OssFileUtils
                    .uploadByAliYun(inputStream, ossConfig, imageId, multipartFile.getContentType(),
                            OssFileUtils.IMAGE);
            return fileName;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }
}